package com.chinawayltd.ews.sample.service.order.impl;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections4.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.chinawayltd.ews.sample.core.exception.BusinessException;
import com.chinawayltd.ews.sample.mapper.TBranchMapper;
import com.chinawayltd.ews.sample.mapper.TLogMapper;
import com.chinawayltd.ews.sample.mapper.TMaterielMapper;
import com.chinawayltd.ews.sample.mapper.TOrderDetailMapper;
import com.chinawayltd.ews.sample.mapper.TOrderMapper;
import com.chinawayltd.ews.sample.mapper.basicInfo.DictExtendMapper;
import com.chinawayltd.ews.sample.mapper.material.MaterielExtendMapper;
import com.chinawayltd.ews.sample.mapper.order.OrderExtendMapper;
import com.chinawayltd.ews.sample.model.TBranch;
import com.chinawayltd.ews.sample.model.TBranchExample;
import com.chinawayltd.ews.sample.model.TBranchExample.Criteria;
import com.chinawayltd.ews.sample.model.TLog;
import com.chinawayltd.ews.sample.model.TMateriel;
import com.chinawayltd.ews.sample.model.TMaterielExample;
import com.chinawayltd.ews.sample.model.TOrder;
import com.chinawayltd.ews.sample.model.TOrderDetail;
import com.chinawayltd.ews.sample.model.TOrderDetailExample;
import com.chinawayltd.ews.sample.model.TOrderExample;
import com.chinawayltd.ews.sample.model.order.InterfaceVO;
import com.chinawayltd.ews.sample.model.order.OrderDetailVO;
import com.chinawayltd.ews.sample.model.order.OrderVO;
import com.chinawayltd.ews.sample.service.base.impl.BaseServiceImpl;
import com.chinawayltd.ews.sample.service.order.OrderService;
import com.chinawayltd.ews.sample.util.PageData;
import com.chinawayltd.ews.sample.util.StringUtils;
import com.chinawayltd.ews.sample.util.excel.ExcelObjModel;
import com.chinawayltd.ews.sample.util.excel.ExportCloumsModel;
import com.chinawayltd.ews.sample.web.query.InterfaceGirdQuery;
import com.chinawayltd.ews.sample.web.query.OrderDetailGirdQuery;
import com.chinawayltd.ews.sample.web.query.OrderGirdQuery;

/**
 * @program: greeProject
 * @description 物料订单service实现
 * @author: chenxin
 * @create: 2018年4月16日 下午5:13:49
 */
@Service
public class OrderServiceImpl extends BaseServiceImpl implements OrderService {
	private static final SimpleDateFormat YYYYMMDD_1 = new SimpleDateFormat("yyyyMMddhhmmss");
	private static final SimpleDateFormat YYYYMMDD = new SimpleDateFormat("yyyy/MM/dd");
	private static final SimpleDateFormat YYYYMMDDHHMMSS = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	private static final SimpleDateFormat YYYYMMDDHHMMSS_ = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
	private static final SimpleDateFormat HHMMSS = new SimpleDateFormat("hh:mm:ss");

	@Autowired
	private OrderExtendMapper orderExtendMapper;
	@Autowired
	private TOrderMapper tOrderMapper;
	@Autowired
	private TOrderDetailMapper tOrderDetailMapper;
	@Autowired
	TBranchMapper tBranchMapper;
	@Autowired
	TMaterielMapper tMaterielMapper;
	@Autowired
	MaterielExtendMapper materielExtendMapper;
	@Autowired
	DictExtendMapper dictExtendMapper;
	

	@Autowired
	private TLogMapper tLogMapper;
	private final String tableNameOrder = "T_ORDER";
	private final String tableNameMateriel = "T_MATERIEL";
	@Override
	public List<OrderVO> listOrderByPage(OrderGirdQuery queryParam) {
		String ids = queryParam.getOrderIds();
		if (StringUtils.isNotBlank(ids)) {
			String[] idsStr = ids.split(",");
			queryParam.setIds(idsStr);
		}
		if(StringUtils.isBlank(queryParam.getSortStr())){
    		queryParam.setSort(0);
    		queryParam.setSortStr("order_date DESC,early_delivery_time,generate_status DESC");
    	}
		List<OrderVO> orderVOList = orderExtendMapper.listOrderByPage(queryParam);
		return orderVOList;
	}

	@Override
	public List<OrderVO> listAbnormalOrderByPage(OrderGirdQuery queryParam) {
		if(StringUtils.isBlank(queryParam.getSortStr())){
    		queryParam.setSort(0);
    		queryParam.setSortStr("order_date DESC,early_delivery_time,generate_status DESC");
    	}
		return orderExtendMapper.listAbnormalOrderByPage(queryParam);
	}

	@Override
	public OrderVO getOrderById(Long id) throws Exception {
		// 判断id是否为空
		if (id == null || id <= 0) {
			throw new RuntimeException("id不能为空或者少于等于0！");
		}
		return orderExtendMapper.getById(id);
	}

	@Override
	@Transactional
	public void insertOrder(OrderVO orderVO) throws Exception {
		Date date = new Date();
		String nowDate = YYYYMMDD_1.format(date);
		
		if(StringUtils.isBlank(orderVO.getOrderNo())){
			throw new BusinessException("订单编号不能为空，添加失败");
		}
		TBranch startBranch = tBranchMapper.selectByPrimaryKey(orderVO.getStartPlaceId());
		Byte branchFromType = startBranch.getBranchFromType();
		Byte branchFromTypew= (byte) 0;
		if (branchFromType !=branchFromTypew) {
			throw new BusinessException("装货点不是配件厂站点！");
		}
		TBranch endBranch = tBranchMapper.selectByPrimaryKey(orderVO.getEndPlaceId());
		Byte branchFromType2 = endBranch.getBranchFromType();
		Byte branchFromTypeww= (byte) 1;
		if (branchFromType2 !=branchFromTypeww) {
			throw new BusinessException("卸货点不是总装厂站点！");
		}
		Long earlyDelivery = YYYYMMDDHHMMSS.parse(orderVO.getEarlyDeliveryTimeStr()).getTime()+ 21600000;
		Long lastDelivery = YYYYMMDDHHMMSS.parse(orderVO.getLastDeliveryTimeStr()).getTime();
		if(earlyDelivery > lastDelivery){
			throw new BusinessException("最早卸货时间要比最晚卸货时间早6个小时以上！");
		}
		
		List<OrderDetailVO> orderDetailList = orderVO.getOrderDetailList();
		if(orderDetailList ==null || orderDetailList.size() <= 0){
			throw new BusinessException("订单物料明细不能为空!");
		}
		boolean flag = this.judgeTransportUnit(orderVO);
		if(!flag){
			throw new BusinessException("订单总板位数与装货站点、卸货站点的车辆不可用车型不符合!");
		}
		orderVO.setEarlyDeliveryTime(YYYYMMDDHHMMSS.parse(orderVO.getEarlyDeliveryTimeStr()));
		orderVO.setLastDeliveryTime(YYYYMMDDHHMMSS.parse(orderVO.getLastDeliveryTimeStr()));
		orderVO.setEntrySource((byte) 1);
		orderVO.setSysOrderNo(orderVO.getOrderNo()+ "-" + nowDate + "-" + 1);
		if (orderVO.getOrderDate() == null) {
			orderVO.setOrderDate(date);
		}
		
		String orderNo = orderVO.getOrderNo();
		String startPlaceId = orderVO.getStartPlaceId() != null ? orderVO.getStartPlaceId().toString() : "";
		String endPlaceId = orderVO.getEndPlaceId() != null ? orderVO.getEndPlaceId().toString() : "";
		String earlyDeliveryTime = orderVO.getEarlyDeliveryTime() != null ? YYYYMMDDHHMMSS.format(orderVO.getEarlyDeliveryTime()) : "";
		String lastDeliveryTime = orderVO.getLastDeliveryTime() != null ? YYYYMMDDHHMMSS.format(orderVO.getLastDeliveryTime()) : "";
		
		String identificationName = orderNo+"/"+startPlaceId+"/"+endPlaceId+"/"+earlyDeliveryTime+"/"+lastDeliveryTime;
		TOrderExample example = new TOrderExample();
		example.createCriteria().andIdentificationNameEqualTo(identificationName);
		List<TOrder> selectIdenNameList = tOrderMapper.selectByExample(example);
		if(selectIdenNameList!=null && !selectIdenNameList.isEmpty()){
			throw new BusinessException("该订单组成的唯一标识已存在,增加失败!");
		}
		orderVO.setIdentificationName(identificationName);

		orderVO.setCreateTime(date);
		orderVO.setUpdateTime(date);
		orderVO.setGenerateStatus((byte) 0);
		orderVO.setExecuteStatus((byte) 0);
		// 增加订单信息
		int orderAdd = orderExtendMapper.insert(orderVO);
		// 增加订单对应的物料明细信息
		if (orderAdd > 0) {
			//添加明细
			insertOrderDetail(orderVO, date);
			//添加日志
			insertLog(orderVO.getId(), 1, date);
		}
	}

	@Override
	public void updateOrder(OrderVO orderVO) throws Exception {
		Date date = new Date();
		int orderUpdate = 0;
		if(StringUtils.isBlank(orderVO.getId().toString())){
			 throw new BusinessException("数据或ID不能为空,修改失败!");
		}
		if(orderVO.getGenerateStatus() ==null || orderVO.getGenerateStatus() !=0){
			throw new BusinessException("订单已调度，修改失败");
		}
		
		TBranch startBranch = tBranchMapper.selectByPrimaryKey(orderVO.getStartPlaceId());
		Byte branchFromType = startBranch.getBranchFromType();
		Byte branchFromTypew= (byte) 0;
		if (branchFromType !=branchFromTypew) {
			throw new BusinessException("装货点不是配件厂站点！");
		}
		
		TBranch endBranch = tBranchMapper.selectByPrimaryKey(orderVO.getEndPlaceId());
		Byte branchFromType2 = endBranch.getBranchFromType();
		Byte branchFromTypeww= (byte) 1;
		if (branchFromType2 !=branchFromTypeww) {
			throw new BusinessException("卸货点不是总装厂站点！");
		}
		
		Long earlyDelivery = YYYYMMDDHHMMSS.parse(orderVO.getEarlyDeliveryTimeStr()).getTime()+ 21600000;
		Long lastDelivery = YYYYMMDDHHMMSS.parse(orderVO.getLastDeliveryTimeStr()).getTime();
		if(earlyDelivery > lastDelivery){
			throw new BusinessException("最早卸货时间要比最晚卸货时间早6个小时以上！");
		}
		List<OrderDetailVO> orderDetailList = orderVO.getOrderDetailList();
		if(orderDetailList ==null || orderDetailList.size() <= 0){
			throw new BusinessException("订单物料明细不能为空!");
		}
		boolean flag = this.judgeTransportUnit(orderVO);
		if(!flag){
			throw new BusinessException("订单总板位数与装货站点、卸货站点的车辆不可用车型不符合!");
		}
		
		// 修改订单信息 ,需要查询出来再修改
		TOrder order = tOrderMapper.selectByPrimaryKey(orderVO.getId());
		if (order != null) {
			order.setSysOrderNo(orderVO.getSysOrderNo());
			order.setStartPlaceId(orderVO.getStartPlaceId());
			order.setEndPlaceId(orderVO.getEndPlaceId());
			orderVO.setEarlyDeliveryTime(YYYYMMDDHHMMSS.parse(orderVO.getEarlyDeliveryTimeStr()));
			orderVO.setLastDeliveryTime(YYYYMMDDHHMMSS.parse(orderVO.getLastDeliveryTimeStr()));
			
			order.setOrderDate(orderVO.getOrderDate());
			order.setApplyDepartment(orderVO.getApplyDepartment());
			order.setTransportUnit(orderVO.getTransportUnit());
			order.setUpdateTime(date);
			
			String orderNo = order.getOrderNo();
			String startPlaceId = orderVO.getStartPlaceId() != null ? orderVO.getStartPlaceId().toString() : "";
			String endPlaceId = orderVO.getEndPlaceId() != null ? orderVO.getEndPlaceId().toString() : "";
			String earlyDeliveryTime = orderVO.getEarlyDeliveryTime() != null ? YYYYMMDDHHMMSS.format(orderVO.getEarlyDeliveryTime()) : "";
			String lastDeliveryTime = orderVO.getLastDeliveryTime() != null ? YYYYMMDDHHMMSS.format(orderVO.getLastDeliveryTime()) : "";
			//order.setIdentificationName(orderNo+"/"+startPlaceId+"/"+endPlaceId+"/"+earlyDeliveryTime+"/"+lastDeliveryTime);
			String identificationName = orderNo+"/"+startPlaceId+"/"+endPlaceId+"/"+earlyDeliveryTime+"/"+lastDeliveryTime;
			TOrderExample example = new TOrderExample();
			example.createCriteria().andIdentificationNameEqualTo(identificationName);
			List<TOrder> selectIdenNameList = tOrderMapper.selectByExample(example);
			if(selectIdenNameList!=null && !selectIdenNameList.isEmpty()){
				for (TOrder tOrder : selectIdenNameList) {
					if(!tOrder.getId().equals(order.getId())){
						throw new BusinessException("该订单组成的唯一标识已存在,修改失败!");
					}
				}
			}
			orderVO.setIdentificationName(identificationName);
			tOrderMapper.updateByPrimaryKeySelective(order);
			updateOrderDetail(orderVO, date, orderDetailList);
			//添加日志
			insertLog(order.getId(), 2, date);
		}
	
	}

	private void updateOrderDetail(OrderVO orderVO, Date date, List<OrderDetailVO> orderDetailList)
			throws BusinessException {
		TOrderDetail orderDetail = null;
		for (OrderDetailVO orderDetailVO : orderDetailList) {
			orderDetail = new TOrderDetail();
			//0不做任何处理1增加2修改3删除
			if ("1".equals(orderDetailVO.getChange())) {// 增加物料明细
				addOrderDetail(orderVO, orderDetail, orderDetailVO);
			} else if ("2".equals(orderDetailVO.getChange())) {// 修改此物料明细
				if(orderDetailVO.getPlanNumber() ==null || orderDetailVO.getPlanNumber() <=0) throw new BusinessException("订单存在物料数量小于等于0");
				if(orderDetailVO.getTransportBoard() ==null) throw new BusinessException("订单板位数不能小于等于0");
				BigDecimal bigDecimal = new BigDecimal(0);
				if(orderDetailVO.getTransportBoard().compareTo(bigDecimal) <=0) throw new BusinessException("订单板位数不能小于等于0");
				orderDetail = tOrderDetailMapper.selectByPrimaryKey(orderDetailVO.getId());
				orderDetail.setMaterielId(orderDetailVO.getMaterielId()); // 物料id
				orderDetail.setPlanNumber(orderDetailVO.getPlanNumber());// 计划数量
				//orderDetail.setActualNumber(orderDetailVO.getActualNumber());// 实际数量
				orderDetail.setTransportBoard(orderDetailVO.getTransportBoard());
				orderDetail.setUnloadingLift(orderDetailVO.getUnloadingLift());
				orderDetail.setUpdateTime(date);
				tOrderDetailMapper.updateByPrimaryKeySelective(orderDetail);
			} else if ("3".equals(orderDetailVO.getChange())) {// 删除此物料明细
				orderDetail = tOrderDetailMapper.selectByPrimaryKey(orderDetailVO.getId());
				if (orderDetail != null) {
					tOrderDetailMapper.deleteByPrimaryKey(orderDetailVO.getId());
				}
			}
		}
	}

	private void addOrderDetail(OrderVO orderVO, TOrderDetail orderDetail, OrderDetailVO orderDetailVO)
			throws BusinessException {
		if(orderDetailVO.getPlanNumber() ==null || orderDetailVO.getPlanNumber() <=0) throw new BusinessException("订单存在物料数量小于等于0");
		BigDecimal bigDecimal = new BigDecimal(0);
		if(orderDetailVO.getTransportBoard() ==null) throw new BusinessException("订单板位数不能小于等于0");
		if(orderDetailVO.getTransportBoard().compareTo(bigDecimal) <=0) throw new BusinessException("订单板位数不能小于等于0");
		orderDetail.setOrderId(orderVO.getId());// 订单id
		orderDetail.setMaterielId(orderDetailVO.getMaterielId()); // 物料id
		orderDetail.setPlanNumber(orderDetailVO.getPlanNumber());// 计划数量
		//orderDetail.setActualNumber(orderDetailVO.getActualNumber());// 实际数量
		orderDetail.setTransportBoard(orderDetailVO.getTransportBoard());
		orderDetail.setUnloadingLift(orderDetailVO.getUnloadingLift());
		orderDetail.setId(null);//防止前端传值
		orderDetail.setCreateTime(new Date());
		orderDetail.setUpdateTime(new Date());
		orderExtendMapper.insertDetail(orderDetail);
	}

	private void insertOrderDetail(OrderVO orderVO, Date date) {
		List<OrderDetailVO> orderDetailList = orderVO.getOrderDetailList();
		TOrderDetail orderDetail = null;
		for (OrderDetailVO orderDetailVO : orderDetailList) {
			orderDetail = new TOrderDetail();
			addOrderDetail(orderVO, orderDetail, orderDetailVO);
		}
	}

	private void insertLog(Long orderId, int i, Date date) {
		// 增加日记
		TLog log = new TLog();
		log.setDataId(orderId);
		log.setTableName(tableNameOrder);
		log.setOperationUser(getCurrentUser().getRealname());
		log.setOperationType(i);
		log.setCreateTime(date);
		tLogMapper.insertSelective(log);
	}

	/**判断订单的总板位数与站点的不可用车型是否符合
	 * @author Fay
	 * @date 2018年5月28日 下午6:00:02
	 * @param orderVO
	 * @return
	 */
	private boolean judgeTransportUnit(OrderVO orderVO) throws Exception{
		List<OrderDetailVO> orderDetailList = orderVO.getOrderDetailList();
		BigDecimal totalTransportBoard = new BigDecimal(0);
		for(OrderDetailVO orderDetailVO : orderDetailList){
			if(!"3".equals(orderDetailVO.getChange())){
				BigDecimal transportBoard = orderDetailVO.getTransportBoard();
				if(transportBoard ==null) throw new BusinessException("订单板位数不能小于等于0");
				BigDecimal bigDecimal = new BigDecimal(0);
				if(transportBoard.compareTo(bigDecimal) <=0) throw new BusinessException("订单板位数不能小于等于0");
				totalTransportBoard = totalTransportBoard.add(transportBoard);
			}
		}
		Map<String, Object> judgeTransportUnitFitBranch = judgeTransportUnitFitBranch(orderVO.getStartPlaceId(), orderVO.getEndPlaceId(), totalTransportBoard);
		if(!MapUtils.getBooleanValue(judgeTransportUnitFitBranch, "flag")){
			return false;//false为不符合站点的不可用车型
		}
		//更新订单的总板位数为最大值
		if(orderVO.getTransportUnit().compareTo(totalTransportBoard) <0 ){
			orderVO.setTransportUnit(totalTransportBoard);
		}
		return true;
	}
	
	@Override
	public int deleteOrderById(Long id) {
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		// 删除订单明细
		orderExtendMapper.deleteDetail(id);// 不管有没有明细都要执行删除
		// 删除订单
		int del = tOrderMapper.deleteByPrimaryKey(id);
		if (del > 0) {
			insertLog(id, 3, new Date());
		}
		return del;
	}

	@Override
	public List<OrderDetailVO> listOrderDetailByOrderId(Long orderId) throws Exception {
		// 判断id是否为空
		if (orderId == null || orderId <= 0) {
			throw new RuntimeException("数据不能为空或者ID等于0！");
		}
		return orderExtendMapper.listOrderDetailByOrderId(orderId);
	}

	@Override
	public List<OrderDetailVO> listOrderDetailByPage(OrderDetailGirdQuery queryParam) throws Exception {
		// 判断id是否为空
		if (queryParam.getOrderId() == null || queryParam.getOrderId() <= 0) {
			throw new RuntimeException("数据不能为空或者ID等于0！");
		}
		return orderExtendMapper.listOrderDetailByPage(queryParam);
	}
	
	@Override
	public OrderVO listOrderByOrderId(Long id) {
		OrderVO orderVo = orderExtendMapper.listOrderByOrderId(id);
		if(orderVo != null){
			Long startPlaceId = orderVo.getStartPlaceId();
			Long endPlaceId = orderVo.getEndPlaceId();
			
			TBranch startBranch = tBranchMapper.selectByPrimaryKey(startPlaceId);
			TBranch endBranch = tBranchMapper.selectByPrimaryKey(endPlaceId);

			int biggerTransportUnit1 = getBiggerTransportUnit(startBranch.getUnavailableCarType());
			int biggerTransportUnit2 = getBiggerTransportUnit(endBranch.getUnavailableCarType());
			if(biggerTransportUnit1 == biggerTransportUnit2){
				orderVo.setMaxTransportUnit(biggerTransportUnit1);
			}else{
				int min = biggerTransportUnit1 > biggerTransportUnit2 ? biggerTransportUnit2 : biggerTransportUnit1;
				orderVo.setMaxTransportUnit(min);
			}
		}
		return orderVo;
	}

	@Override
	public List<OrderVO> listOrderByOrderIdOrOrderNo(Long orderId, String orderNo) {
		return orderExtendMapper.listOrderByOrderIdOrOrderNo(orderId, orderNo);
	}

	@Override
	public List<OrderVO> listOrderByTaskId(Long taskId) {
		return orderExtendMapper.listOrderByTaskId(taskId);
	}

	@Override
	public List<OrderDetailVO> listOrderDetailByOrderIdOrOrderNo(Long orderId, String orderNo) {
		return orderExtendMapper.listOrderDetailByOrderIdOrOrderNo(orderId, orderNo);
	}

	@Override
	public int updateOrderDetail(TOrderDetail od) {
		TOrderDetail orderDetail = tOrderDetailMapper.selectByPrimaryKey(od.getId());
		orderDetail.setPlanNumber(od.getPlanNumber());
		orderDetail.setActualNumber(od.getActualNumber());
		orderDetail.setUpdateTime(new Date());
		return tOrderDetailMapper.updateByPrimaryKey(orderDetail);
	}

	/**
	 * 判断物料编码是否存在
	 * 
	 * @author Fay
	 * @date 2018年5月8日 下午2:10:00
	 * @param materielNo
	 * @return
	 */
	private Map<String, Object> judgeMaterielNoExist(String materielNo) {
		Map<String, Object> resultMap = new HashMap<>();

		TMaterielExample example = new TMaterielExample();
		example.createCriteria().andMaterielNoEqualTo(materielNo);
		List<TMateriel> selectByExample = tMaterielMapper.selectByExample(example);
		if (selectByExample.size() > 0) {
			resultMap.put("id", selectByExample.get(0).getId());
			resultMap.put("flag", 1);
		} else {
			resultMap.put("flag", 0);
		}
		return resultMap;
	}

	/**
	 * 订单板位数不能超过车辆最大板位数（结合取货点和送货点的车型限制，如果没有限制最大板位不能超过30）
	 * 
	 * @author Fay
	 * @date 2018年5月22日 上午10:08:53
	 * @param startPlaceId
	 * @param endPlaceId
	 * @param transportUnit
	 * @return
	 */
	private Map<String, Object> judgeTransportUnitFitBranch(Long startPlaceId, Long endPlaceId,
			BigDecimal transportUnit) {
		Map<String, Object> resultMap = new HashMap<>();
		TBranch startBranch = tBranchMapper.selectByPrimaryKey(startPlaceId);
		TBranch endBranch = tBranchMapper.selectByPrimaryKey(endPlaceId);
		String unavailableCarType1 = startBranch.getUnavailableCarType();//得到不可用车型板位
		String unavailableCarType2 = endBranch.getUnavailableCarType();//得到不可用车型板位
		boolean flag1 = this.compareToTransportUnit(transportUnit, unavailableCarType1);
		if (!flag1) {
			resultMap.put("flag", false);
			resultMap.put("describe", "由于装货站点车型板位限制，板位数不符合该装货站点的限制板位数，如果没有限制最大板位则不能超过30");
			return resultMap;
		}
		boolean flag2 = this.compareToTransportUnit(transportUnit, unavailableCarType2);
		if (!flag2) {
			resultMap.put("flag", false);
			resultMap.put("describe", "由于卸货站点车型板位限制，板位数不符合该卸货站点的限制板位数，如果没有限制最大板位则不能超过30");
			return resultMap;
		}
		resultMap.put("flag", true);
		return resultMap;
	}

	private boolean compareToTransportUnit(BigDecimal transportUnit, String unavailableCarType) {
		
		if (org.apache.commons.lang3.StringUtils.isNoneBlank(unavailableCarType)) {
			int bigger = getBiggerTransportUnit(unavailableCarType);//获取该站点的最大版位数

			String transportUnitType = bigger + "";
			BigDecimal typeNum = new BigDecimal(transportUnitType);
			if (typeNum.compareTo(transportUnit) < 0) {
				return false;
			}
		} else {
			BigDecimal typeNum = new BigDecimal(30);
			if (typeNum.compareTo(transportUnit) < 0) {
				return false;
			}
		}
		return true;
	}

	/**获取最大可用的车板位
	 * @author Fay
	 * @date 2018年5月28日 下午5:41:35
	 * @param unavailableCarType
	 * @return
	 */
	private int getBiggerTransportUnit(String unavailableCarType) {
		List<String> transportUnitArr = new ArrayList<>();
		//List<String> transportUnitList = dictExtendMapper.getTransportUnitByDict();
		transportUnitArr.add("30");
		transportUnitArr.add("20");
		transportUnitArr.add("16");
		int bigger = 0 ;
		if(org.apache.commons.lang3.StringUtils.isNoneBlank(unavailableCarType)){
			String[] split = unavailableCarType.split(",");
			//除去不可用车型//如20
			for (String num : split) {
				for (int i = 0; i < transportUnitArr.size(); i++) {
					String string = transportUnitArr.get(i);
					if (string.equals(num)) {
						transportUnitArr.remove(i);
					}
				}
			}
			//剩下30，16
			if (transportUnitArr != null && transportUnitArr.size() > 0) {
				for (String type : transportUnitArr) {
					if (Integer.valueOf(type) > bigger) {
						bigger = Integer.valueOf(type);
					}
				}
			} else {
				bigger = 30;
			}
		}else{
			bigger = 30;
		}
		return bigger;
	}

	/**
	 * 判断站点是否存在
	 * 
	 * @author Fay
	 * @date 2018年5月7日 下午7:06:50
	 * @return
	 */
	private Map<String, Object> judgePlaceExist(String placeName) {
		Map<String, Object> resultModel = new HashMap<>();

		TBranchExample branchNameExample = new TBranchExample();
		Criteria branchNameCriteria = branchNameExample.createCriteria();
		branchNameCriteria.andBranchNameEqualTo(placeName);
		List<TBranch> tBranchList = tBranchMapper.selectByExample(branchNameExample);
		if (tBranchList.size() > 0) {
			// 如果存在
			// 如果获取的数据List只有一条证明只有一条站点信息，如果有多条证明有重复的数据，那也就只拿第一条数据
			Long branchId = tBranchList.get(0).getId();
			resultModel.put("id", branchId);
			resultModel.put("flag", 1);
			return resultModel;
		} else {
			// 如果不存在
			resultModel.put("flag", 0);
			return resultModel;
		}
	}

	@Override
	public int updateOrderExecutStateByTaskId(int i, Long taskId, Date date) throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("statusNum", i);
		map.put("taskId", taskId);
		map.put("updateTime", date);
		return orderExtendMapper.updateOrderExecutState(map);
	}

	public static void main(String[] args) {
		try {
			Date parse = HHMMSS.parse("2018-12-12 12:00");
			System.out.println(parse);
		} catch (ParseException e) {
			e.printStackTrace();
		}
		System.out.println("gogogo");
	}

	@Override
	public List<Map<String, Object>> exportGirdData(OrderGirdQuery queryParam) {
		String ids = queryParam.getOrderIds();
		if (StringUtils.isNotBlank(ids)) {
			String[] idsStr = ids.split(",");
			queryParam.setIds(idsStr);
		}
		return orderExtendMapper.listOrderToMap(queryParam);
	}

	@Override
	public List<Map<String, Object>> abnormalExportGirdData(OrderGirdQuery queryParam) {
		return orderExtendMapper.listAbnormalOrderToMap(queryParam);
	}

	@Override
	@Transactional
	public ExcelObjModel insertList(List<PageData> list) {
		ExcelObjModel model = new ExcelObjModel();
		model.setCode(0); // 0没添加1添加成功，否则有添加不成功的
		
		Map<Integer, Map> indexMap = new HashMap<>();
		Map<String, Map<Integer, OrderVO>> sameOrderMap = new HashMap<>();//相同订单号的放入同一个key
		int index = 0;
		errorContinue : for (PageData pd : list) {
			index = index+1;
			try {
				Map<String, Object> orderMap = new HashMap<>();
				OrderVO order = new OrderVO();
				OrderDetailVO orderDetailVO = new OrderDetailVO();
				String orderDate = pd.getString("var0");
				orderMap.put("orderDate", orderDate);
				SimpleDateFormat sdf = YYYYMMDD;
				if (StringUtils.isNoneBlank(orderDate)) {
					if(orderDate.length() ==19){//时间
						sdf = YYYYMMDDHHMMSS;
						order.setOrderDate(sdf.parse(orderDate));
					}else if(orderDate.length() >= 16 && orderDate.length() <19){//时间
						String time = orderDate.split(" ")[1];
						if(time.length() ==8){
							order.setOrderDate(sdf.parse(orderDate));
						}else{
							String ss[] = orderDate.split(" ")[0].split("/");
							Calendar ci = Calendar.getInstance();
							ci.set(Integer.parseInt(ss[0]), Integer.parseInt(ss[1])-1,Integer.parseInt(ss[2]),0,0,0);
							order.setOrderDate(ci.getTime());
						}
					}else{
						String ss[] = orderDate.split(" ")[0].split("/");
						Calendar ci = Calendar.getInstance();
						ci.set(Integer.parseInt(ss[0]), Integer.parseInt(ss[1])-1,Integer.parseInt(ss[2]),0,0,0);
						order.setOrderDate(ci.getTime());
					}
				}
				
				String orderNo = pd.getString("var1");
				orderMap.put("orderNo", orderNo);
				order.setOrderNo(orderNo);
				String startPlaceName = pd.getString("var2");
				orderMap.put("startPlaceName", startPlaceName);
				order.setStartPlaceName(startPlaceName);
				String endPlaceName = pd.getString("var3");
				orderMap.put("endPlaceName", endPlaceName);
				order.setEndPlaceName(endPlaceName);
				String earlyDeliveryTime = pd.getString("var4");
				orderMap.put("earlyDeliveryTime", YYYYMMDDHHMMSS_.format(YYYYMMDDHHMMSS.parse(earlyDeliveryTime)));
				if (StringUtils.isNoneBlank(earlyDeliveryTime)) {
					order.setEarlyDeliveryTime(YYYYMMDDHHMMSS.parse(earlyDeliveryTime));
				}
				String lastDeliveryTime = pd.getString("var5");
				orderMap.put("lastDeliveryTime", YYYYMMDDHHMMSS_.format(YYYYMMDDHHMMSS.parse(lastDeliveryTime)));
				if (StringUtils.isNoneBlank(lastDeliveryTime)) {
					order.setLastDeliveryTime(YYYYMMDDHHMMSS.parse(lastDeliveryTime));
				}

				String applyDepartment = pd.getString("var6");
				orderMap.put("applyDepartment", applyDepartment);
				order.setApplyDepartment(applyDepartment);

				String materielNo = pd.getString("var7");
				orderMap.put("materielNo", materielNo);
				orderDetailVO.setMaterielNo(materielNo);
				String materielName = pd.getString("var8");
				orderMap.put("materielName", materielName);
				orderDetailVO.setMaterielName(materielName);
				String transportBoard = pd.getString("var9");
				orderMap.put("transportBoard", transportBoard);
				if (StringUtils.isNoneBlank(transportBoard)) {
					orderDetailVO.setTransportBoard(new BigDecimal(transportBoard).setScale(6, BigDecimal.ROUND_UP));
				}
				String planNumber = pd.getString("var10");
				orderMap.put("planNumber", planNumber);
				if (StringUtils.isNoneBlank(planNumber)) {
					orderDetailVO.setPlanNumber(Integer.valueOf(planNumber));
				}
				String unloadingLift = pd.getString("var11");
				orderMap.put("unloadingLift", unloadingLift);
				orderDetailVO.setUnloadingLift(unloadingLift);
				for (int i = 0; i < 12; i++) {
					if (StringUtils.isBlank(pd.getString("var" + i)) && i != 6 && i != 11) {
						int com = i + 1;
						orderMap.put("describe", "第" + com + "列填写的字段不能为空");
						indexMap.put(index - 1, orderMap);
						continue errorContinue;
					}
				}
				// 判断是否存在站点
				Map<String, Object> startPlaceFalg = this.judgePlaceExist(startPlaceName);
				if (MapUtils.getInteger(startPlaceFalg, "flag") > 0) {
					order.setStartPlaceId(MapUtils.getLong(startPlaceFalg, "id"));
				} else {
					// 如果不存在，则记录错误
					orderMap.put("describe", "不存在" + startPlaceName + "站点");
					indexMap.put(index - 1, orderMap);
					continue;
				}
				Map<String, Object> endPlaceFalg = this.judgePlaceExist(endPlaceName);
				if (MapUtils.getInteger(endPlaceFalg, "flag") > 0) {
					order.setEndPlaceId(MapUtils.getLong(endPlaceFalg, "id"));
				} else {
					orderMap.put("describe", "不存在" + endPlaceName + "站点");
					indexMap.put(index - 1, orderMap);
					continue;
				}
				if (HHMMSS.format(YYYYMMDDHHMMSS.parse(lastDeliveryTime)).equals("00:00:00")) {
					orderMap.put("describe", "结束时间不能为00:00:00");
					indexMap.put(index - 1, orderMap);
					continue;
				}
				// 送货时间对比
				if (YYYYMMDDHHMMSS.parse(earlyDeliveryTime).getTime() > YYYYMMDDHHMMSS.parse(lastDeliveryTime)
						.getTime()) {
					orderMap.put("describe", "最早送货时间要小于最晚送货时间");
					indexMap.put(index - 1, orderMap);
					continue;
				}
				//合并
				List<OrderDetailVO> newOrderDList = new ArrayList<>();
				newOrderDList.add(orderDetailVO);
				order.setOrderDetailList(newOrderDList);
				
				String identificationName = orderNo+"/"+order.getStartPlaceId()+"/"+order.getEndPlaceId()+"/"+YYYYMMDDHHMMSS.format(order.getEarlyDeliveryTime())+"/"+YYYYMMDDHHMMSS.format(order.getLastDeliveryTime());
				Map<Integer, OrderVO> orderVoList = sameOrderMap.get(identificationName);
				if(orderVoList != null && orderVoList.size() > 0){
					orderVoList.put(index-1, order);
				}else{
					Map<Integer, OrderVO> newMap = new HashMap<>();
					newMap.put(index-1, order);
					//将一样的一订单四条件的放入同一个地方
					sameOrderMap.put(identificationName, newMap);
				}
				
			} catch (Exception e) {
				Map<String, Object> exceptionMap = new HashMap<>();
				exceptionMap.put("orderDate", pd.getString("var0"));
				exceptionMap.put("orderNo", pd.getString("var1"));
				exceptionMap.put("startPlaceName", pd.getString("var2"));
				exceptionMap.put("endPlaceName", pd.getString("var3"));
				exceptionMap.put("earlyDeliveryTime", pd.getString("var4"));
				exceptionMap.put("lastDeliveryTime", pd.getString("var5"));
				exceptionMap.put("applyDepartment", pd.getString("var6"));
				exceptionMap.put("materielNo", pd.getString("var7"));
				exceptionMap.put("materielName", pd.getString("var8"));
				exceptionMap.put("transportBoard", pd.getString("var9"));
				exceptionMap.put("planNumber", pd.getString("var10"));
				exceptionMap.put("unloadingLift", pd.getString("var11"));
				exceptionMap.put("describe", "数据异常，导入失败");
				indexMap.put(index - 1, exceptionMap);
			}
		}
		Map<Integer, Map> result = this.handleData(sameOrderMap);
		indexMap.putAll(result);
		List<Object> resultList = new ArrayList<>();
		for(int i = 0 ; i < indexMap.size(); i++ ){
			if(indexMap.get(i) != null){
				resultList.add(indexMap.get(i));
			}
		}
		model.setCode(1); 
		model.setList(resultList);
		List<ExportCloumsModel> cloums = new ArrayList<>();
		if (resultList.size() > 0) {
			cloums.add(new ExportCloumsModel("订单日期", "orderDate"));
			cloums.add(new ExportCloumsModel("订单号", "orderNo"));
			cloums.add(new ExportCloumsModel("装货点", "startPlaceName"));
			cloums.add(new ExportCloumsModel("卸货点", "endPlaceName"));
			cloums.add(new ExportCloumsModel("最早送货时间", "earlyDeliveryTime"));
			cloums.add(new ExportCloumsModel("最晚送货时间", "lastDeliveryTime"));
			cloums.add(new ExportCloumsModel("申请单位", "applyDepartment"));
			cloums.add(new ExportCloumsModel("物料编码", "materielNo"));
			cloums.add(new ExportCloumsModel("物料名称", "materielName"));
			cloums.add(new ExportCloumsModel("板位数", "transportBoard"));
			cloums.add(new ExportCloumsModel("运输数量", "planNumber"));
			cloums.add(new ExportCloumsModel("卸货电梯口", "unloadingLift"));
			cloums.add(new ExportCloumsModel("导入描述", "describe"));
		}
		model.setCloums(cloums);
		return model;
	}
	private static String[] sources = new String[]{  
	        "A","B","C","D","E","F","G","H",  
	        "I","J","K","L","M","N","O","P",  
	        "Q","R","S","T","U","V","W","X","Y","Z"  
	};
	@Override
	@Transactional
	public ExcelObjModel insertList2(List<PageData> list) {
		ExcelObjModel model = new ExcelObjModel();
		model.setCode(0); // 0没添加1添加成功，否则有添加不成功的
		Date date = new Date();
		String nowDate = YYYYMMDD_1.format(date);
		Map<Integer, Map> indexMap = new HashMap<>();
		Map<String, Map<Integer, OrderVO>> sameOrderMap = new HashMap<>();//相同订单号的放入同一个key
		Map<String, String> sameKeyMap = new HashMap<>();//相同key
		int index = 0;
		int abnormal = 0;
		String abnormalStr = null;//标识异常列、
		TBranch startBranch = null;
		TBranch endBranch = null;
		errorContinue : for (PageData pd : list) {
			index = index+1;
			try {
				Map<String, Object> orderMap = new HashMap<>();
				OrderVO order = new OrderVO();
				OrderDetailVO orderDetailVO = new OrderDetailVO();
				abnormalStr = "A";
				String orderDate = pd.getString("var0");
				orderMap.put("orderDate", orderDate);
				SimpleDateFormat sdf = YYYYMMDD;
				if (StringUtils.isNoneBlank(orderDate)) {
					if(orderDate.length() ==19){//时间
						sdf = YYYYMMDDHHMMSS;
						order.setOrderDate(sdf.parse(orderDate));
					}else if(orderDate.length() >= 16 && orderDate.length() <19){//时间
						String time = orderDate.split(" ")[1];
						if(time.length() ==8){
							order.setOrderDate(sdf.parse(orderDate));
						}else{
							String ss[] = orderDate.split(" ")[0].split("/");
							Calendar ci = Calendar.getInstance();
							ci.set(Integer.parseInt(ss[0]), Integer.parseInt(ss[1])-1,Integer.parseInt(ss[2]),0,0,0);
							order.setOrderDate(ci.getTime());
						}
					}else{
						String ss[] = orderDate.split(" ")[0].split("/");
						Calendar ci = Calendar.getInstance();
						ci.set(Integer.parseInt(ss[0]), Integer.parseInt(ss[1])-1,Integer.parseInt(ss[2]),0,0,0);
						order.setOrderDate(ci.getTime());
					}
				}
				String orderNo = pd.getString("var1");
				orderMap.put("orderNo", orderNo);
				order.setOrderNo(orderNo);
				String startPlaceName = pd.getString("var2");
				orderMap.put("startPlaceName", startPlaceName);
				order.setStartPlaceName(startPlaceName);
				String endPlaceName = pd.getString("var3");
				orderMap.put("endPlaceName", endPlaceName);
				order.setEndPlaceName(endPlaceName);
				abnormalStr = "E";
				String earlyDeliveryTime = pd.getString("var4");
				orderMap.put("earlyDeliveryTime", YYYYMMDDHHMMSS_.format(YYYYMMDDHHMMSS.parse(earlyDeliveryTime)));
				if (StringUtils.isNoneBlank(earlyDeliveryTime)) {
					order.setEarlyDeliveryTime(YYYYMMDDHHMMSS.parse(earlyDeliveryTime));
				}
				abnormalStr = "F";
				String lastDeliveryTime = pd.getString("var5");
				orderMap.put("lastDeliveryTime", YYYYMMDDHHMMSS_.format(YYYYMMDDHHMMSS.parse(lastDeliveryTime)));
				if (StringUtils.isNoneBlank(lastDeliveryTime)) {
					order.setLastDeliveryTime(YYYYMMDDHHMMSS.parse(lastDeliveryTime));
				}

				String applyDepartment = pd.getString("var6");
				orderMap.put("applyDepartment", applyDepartment);
				order.setApplyDepartment(applyDepartment);

				String materielNo = pd.getString("var7");
				orderMap.put("materielNo", materielNo);
				orderDetailVO.setMaterielNo(materielNo);
				String materielName = pd.getString("var8");
				orderMap.put("materielName", materielName);
				orderDetailVO.setMaterielName(materielName);
				abnormalStr = "J";
				String transportBoard = pd.getString("var9");//板位数
				orderMap.put("transportBoard", transportBoard);
				if (StringUtils.isNoneBlank(transportBoard)) {
					orderDetailVO.setTransportBoard(new BigDecimal(transportBoard).setScale(6, BigDecimal.ROUND_UP));
				}else{
					orderDetailVO.setTransportBoard(new BigDecimal(0));
				}
				order.setTransportUnit(orderDetailVO.getTransportBoard());
				abnormalStr = "K";
				String planNumber = pd.getString("var10");//运输数量
				orderMap.put("planNumber", planNumber);
				if (StringUtils.isNoneBlank(planNumber)) {
					orderDetailVO.setPlanNumber(Integer.valueOf(planNumber));
				}
				String unloadingLift = pd.getString("var11");//卸货电梯口
				orderMap.put("unloadingLift", unloadingLift);
				orderDetailVO.setUnloadingLift(unloadingLift);
				for (int i = 0; i < 12; i++) {
					if (StringUtils.isBlank(pd.getString("var" + i)) && i != 6 && i != 11) {
						//int com = i + 1;
						orderMap.put("describe", "第" + sources[i] + "列填写的字段不能为空");
						indexMap.put(index - 1, orderMap);
						abnormal = abnormal+1;
						continue errorContinue;
					}
				}
				if (StringUtils.isNoneBlank(transportBoard)) {
					BigDecimal setScale = new BigDecimal(transportBoard).setScale(6, BigDecimal.ROUND_UP);
					if(setScale.compareTo(new BigDecimal(0))<=0){
						orderMap.put("describe", "第J列：订单板位数不能小于等于0");
						indexMap.put(index - 1, orderMap);
						abnormal = abnormal+1;
						continue errorContinue;
					}
				}else{
					orderMap.put("describe", "第J列：订单板位数不能为空");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				if (StringUtils.isNoneBlank(planNumber)) {
					if(Integer.valueOf(planNumber) <=0){
						orderMap.put("describe", "第K列：订单运输数量不能小于等于0");
						indexMap.put(index - 1, orderMap);
						abnormal = abnormal+1;
						continue errorContinue;
					}
				}else{
					orderMap.put("describe", "第K列：订单运输数量不能为空");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				
				// 判断是否存在站点
				Map<String, Object> startPlaceFalg = this.judgePlaceExist(startPlaceName);
				if (MapUtils.getInteger(startPlaceFalg, "flag") > 0) {
					order.setStartPlaceId(MapUtils.getLong(startPlaceFalg, "id"));
				} else {
					// 如果不存在，则记录错误
					orderMap.put("describe", "第C列：不存在" + startPlaceName + "站点");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				Map<String, Object> endPlaceFalg = this.judgePlaceExist(endPlaceName);
				if (MapUtils.getInteger(endPlaceFalg, "flag") > 0) {
					order.setEndPlaceId(MapUtils.getLong(endPlaceFalg, "id"));
				} else {
					orderMap.put("describe", "第D列：不存在" + endPlaceName + "站点");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				
				if (order.getStartPlaceId() == order.getEndPlaceId()) {
					orderMap.put("describe", "第C和第D列：装货点不能与卸货点相同");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				
				startBranch = tBranchMapper.selectByPrimaryKey(order.getStartPlaceId());
				Byte branchFromType = startBranch.getBranchFromType();
				Byte branchFromTypeww= (byte) 0;
				if (branchFromTypeww !=branchFromType) {
					orderMap.put("describe", "第C列：装货点不是配件厂站点");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				endBranch = tBranchMapper.selectByPrimaryKey(order.getEndPlaceId());
				Byte branchFromType2 = endBranch.getBranchFromType();
				Byte branchFromType2ww= (byte) 1;
				if (branchFromType2ww !=branchFromType2) {
					orderMap.put("describe", "第D列：卸货点不是总装厂站点");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				
				//判断板位数是否与站点的板位数相匹配
				Map<String, Object> judgeTransportUnitFitBranch = this.judgeTransportUnitFitBranch(order.getStartPlaceId(),
						order.getEndPlaceId(), orderDetailVO.getTransportBoard());
				if (!MapUtils.getBoolean(judgeTransportUnitFitBranch, "flag")) {
					orderMap.put("describe", MapUtils.getString(judgeTransportUnitFitBranch, "describe"));
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				
				if (HHMMSS.format(YYYYMMDDHHMMSS.parse(earlyDeliveryTime)).equals("00:00:00")) {
					orderMap.put("describe", "第E列：结束时间不能为00:00:00");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				if (HHMMSS.format(YYYYMMDDHHMMSS.parse(lastDeliveryTime)).equals("00:00:00")) {
					orderMap.put("describe", "第F列：结束时间不能为00:00:00");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				// 送货时间对比
				if (YYYYMMDDHHMMSS.parse(earlyDeliveryTime).getTime() +21600000 > YYYYMMDDHHMMSS.parse(lastDeliveryTime) .getTime()) {
					orderMap.put("describe", "第E和F列：订单最早卸货时间要比最晚卸货时间早6个小时以上！");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				
				//添加订单明细
				List<OrderDetailVO> newOrderDList = new ArrayList<>();
				newOrderDList.add(orderDetailVO);
				order.setOrderDetailList(newOrderDList);
				order.setSysOrderNo(orderNo+"-" + nowDate + "-" + index);
				
				//String identificationName = orderNo+"-" + nowDate + "-" + index+"/"+order.getStartPlaceId()+"/"+order.getEndPlaceId()+"/"+YYYYMMDDHHMMSS.format(order.getEarlyDeliveryTime())+"/"+YYYYMMDDHHMMSS.format(order.getLastDeliveryTime());
				String identificationName = orderNo+"/"+order.getStartPlaceId()+"/"+order.getEndPlaceId()+"/"+YYYYMMDDHHMMSS.format(order.getEarlyDeliveryTime())+"/"+YYYYMMDDHHMMSS.format(order.getLastDeliveryTime()) +"/"+materielNo.trim()+"/"+orderDetailVO.getTransportBoard()+"/"+orderDetailVO.getPlanNumber();
				//查询订单是否存在该标识
				TOrderExample example = new TOrderExample();
				example.createCriteria().andIdentificationNameEqualTo(identificationName);
				List<TOrder> selectIdenNameList = tOrderMapper.selectByExample(example);
				if(selectIdenNameList!=null && !selectIdenNameList.isEmpty()){
					orderMap.put("describe", "该订单已存在，导入失败!");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}
				
				orderMap.put("describe", "数据正常!");//index行数,因为用第二条开始，所以+1
				Map<Integer, OrderVO> orderVoList = sameOrderMap.get(identificationName);//获取相同的行数据
				if(orderVoList != null && orderVoList.size() > 0){//如果还没有，
					String str = sameKeyMap.get(identificationName);
					orderMap.put("describe", "数据与第 "+str+" 行数据重复，导入失败!");
					indexMap.put(index - 1, orderMap);
					abnormal = abnormal+1;
					continue errorContinue;
				}else{
					Map<Integer, OrderVO> newMap = new HashMap<>();
					newMap.put(index-1, order);
					sameOrderMap.put(identificationName, newMap);
					sameKeyMap.put(identificationName, (index+1)+"");//index行数,因为用第二条开始，所以+1
					indexMap.put(index - 1, orderMap);
				}
			} catch (Exception e) {
				Map<String, Object> exceptionMap = new HashMap<>();
				exceptionMap.put("orderDate", pd.getString("var0"));
				exceptionMap.put("orderNo", pd.getString("var1"));
				exceptionMap.put("startPlaceName", pd.getString("var2"));
				exceptionMap.put("endPlaceName", pd.getString("var3"));
				exceptionMap.put("earlyDeliveryTime", pd.getString("var4"));
				exceptionMap.put("lastDeliveryTime", pd.getString("var5"));
				exceptionMap.put("applyDepartment", pd.getString("var6"));
				exceptionMap.put("materielNo", pd.getString("var7"));
				exceptionMap.put("materielName", pd.getString("var8"));
				exceptionMap.put("transportBoard", pd.getString("var9"));
				exceptionMap.put("planNumber", pd.getString("var10"));
				exceptionMap.put("unloadingLift", pd.getString("var11"));
				exceptionMap.put("describe", "第"+abnormalStr+"列：数据异常，导入失败");
				indexMap.put(index - 1, exceptionMap);
				abnormal = abnormal+1;
			}
		}
		if(abnormal <=0){
			Map<Integer, Map> result = this.handleData2(sameOrderMap);
			indexMap.putAll(result);
		}
		List<Object> resultList = new ArrayList<>();
		for(int i = 0 ; i < indexMap.size(); i++ ){
			if(indexMap.get(i) != null){
				resultList.add(indexMap.get(i));
			}
		}
		model.setCode(1);
		model.setList(resultList);
		List<ExportCloumsModel> cloums = new ArrayList<>();
		if (resultList.size() > 0) {
			cloums.add(new ExportCloumsModel("订单日期", "orderDate"));
			cloums.add(new ExportCloumsModel("订单号", "orderNo"));
			cloums.add(new ExportCloumsModel("装货点", "startPlaceName"));
			cloums.add(new ExportCloumsModel("卸货点", "endPlaceName"));
			cloums.add(new ExportCloumsModel("最早卸货时间", "earlyDeliveryTime"));
			cloums.add(new ExportCloumsModel("最晚卸货时间", "lastDeliveryTime"));
			cloums.add(new ExportCloumsModel("申请单位", "applyDepartment"));
			cloums.add(new ExportCloumsModel("物料编码", "materielNo"));
			cloums.add(new ExportCloumsModel("物料名称", "materielName"));
			cloums.add(new ExportCloumsModel("板位数", "transportBoard"));
			cloums.add(new ExportCloumsModel("运输数量", "planNumber"));
			cloums.add(new ExportCloumsModel("卸货电梯口", "unloadingLift"));
			cloums.add(new ExportCloumsModel("导入描述", "describe"));
		}
		model.setCloums(cloums);
		return model;
	}
	
	/**分类好导入的订单信息后，进行数据处理
	 * @author Fay
	 * @date 2018年5月25日 下午1:17:46
	 * @param sameOrderMap
	 * @return
	 * @throws Exception 
	 */
	public Map<Integer, Map> handleData(Map<String, Map<Integer, OrderVO>> sameOrderMap){
		Date date = new Date();
		String nowDate = YYYYMMDD_1.format(date);
		//记录订单的子单号Map
		Map<String, Integer> order_sys_Map = new HashMap<>();
		
		//记录信息在第几条
		Map<Integer, Map> indexMap = new HashMap<>();
		//记录本次同一个orderId只删除一次
		Map<Long, Long> deleteOrderIdMap = new HashMap<>();
		if(sameOrderMap == null){
			return indexMap;
		}
		errorForeach: for(String key : sameOrderMap.keySet()){
			Map<Integer, OrderVO> orderList = sameOrderMap.get(key);
			BigDecimal totalTransportBoard = new BigDecimal(0);
			Integer index_ = null;//记录
			for(Integer index : orderList.keySet()){
				index_ = index;
				OrderVO orderVO = orderList.get(index);
				// 循环时，统计板位数总和，方便等下判断板位数是否符合站点板位数
				List<OrderDetailVO> orderDetailList = orderVO.getOrderDetailList();
				// 导入进来的订单详细只有一条
				OrderDetailVO orderDetailVO = orderDetailList.get(0);
				BigDecimal transportBoard = orderDetailVO.getTransportBoard();
				totalTransportBoard = totalTransportBoard.add(transportBoard);
			}
			//判断板位数是否与站点的板位数相匹配(大家的key值相同，即装货点、卸货点都相同，因此取第一条就可以了)
			Map<String, Object> judgeTransportUnitFitBranch = this.judgeTransportUnitFitBranch(orderList.get(index_).getStartPlaceId(),
					orderList.get(index_).getEndPlaceId(), totalTransportBoard);
			if (!MapUtils.getBoolean(judgeTransportUnitFitBranch, "flag")) {
				for(Integer index : orderList.keySet()){
					OrderVO orderVO = orderList.get(index);
					Map<String, Object> orderMap = getOrderMap(orderVO);
					orderMap.put("describe", MapUtils.getString(judgeTransportUnitFitBranch, "describe"));
					indexMap.put(index, orderMap);
				}
				continue errorForeach;
			}
			//查询订单是否存在该标识
			TOrderExample example = new TOrderExample();
			example.createCriteria().andIdentificationNameEqualTo(key);
			List<TOrder> selectIdenNameList = tOrderMapper.selectByExample(example);
			
			Long orderId = null;
			if(selectIdenNameList != null && selectIdenNameList.size() > 0){
				orderId = selectIdenNameList.get(0).getId();
				Byte executeStatus = selectIdenNameList.get(0).getExecuteStatus();
				Byte generateStatus = selectIdenNameList.get(0).getGenerateStatus();
				if(executeStatus != 0 || generateStatus != 0){
					for(Integer index : orderList.keySet()){
						OrderVO orderVO = orderList.get(index);
						Map<String, Object> orderMap = getOrderMap(orderVO);
						orderMap.put("describe", "由于订单已生成或已执行，因此不能再导入数据");
						indexMap.put(index, orderMap);
					}
					continue errorForeach;
				}
				if(deleteOrderIdMap.get(orderId) == null){
					// 证明存在的话，在原本的订单里面先删除原先的物料详细，再新增。只删除一次
					TOrderDetailExample tOrderDetailExample = new TOrderDetailExample();
					tOrderDetailExample.createCriteria().andOrderIdEqualTo(orderId);
					tOrderDetailMapper.deleteByExample(tOrderDetailExample);
					deleteOrderIdMap.put(orderId, orderId);
				}
				for(Integer index : orderList.keySet()){
					OrderVO orderVO = orderList.get(index);
					Map<String, Object> orderMap = getOrderMap(orderVO);
					Map<String, Object> importMap = importOrderDetail(date, orderId, orderVO);
					if(MapUtils.getInteger(importMap, "flag") == 1){
						orderMap.put("describe", MapUtils.getString(importMap, "describe"));
						indexMap.put(index, orderMap);
					}else{
						orderMap.put("describe", MapUtils.getString(importMap, "describe"));
						indexMap.put(index, orderMap);
						continue errorForeach;
					}
				}
			}else{
				// 不存在该标识证明是一个新订单 
				int i = 0;
				for(Integer index : orderList.keySet()){
					OrderVO orderVO = orderList.get(index);
					Map<String, Object> orderMap2 = getOrderMap(orderVO);
					if(i == 0){//订单重复只需要保存第一个
						i++;
						String sysOrderNo = "";
						Integer sysNo = order_sys_Map.get(orderVO.getOrderNo());
						if(sysNo != null){
							sysNo = sysNo + 1;
							sysOrderNo = orderVO.getOrderNo() + "-" + nowDate + "-" + sysNo;
							order_sys_Map.put(orderVO.getOrderNo(), sysNo);
						}else{
							order_sys_Map.put(orderVO.getOrderNo(), 1);
							sysOrderNo = orderVO.getOrderNo() + "-" + nowDate + "-" + 1;
						}
						orderVO.setSysOrderNo(sysOrderNo);
						orderVO.setCreateTime(date);
						orderVO.setUpdateTime(date);
						orderVO.setTransportUnit(totalTransportBoard);
						orderVO.setIdentificationName(key);
						orderVO.setGenerateStatus((byte)0);
						orderVO.setExecuteStatus((byte)0);
						orderVO.setEntrySource((byte)0);
						int insertOrder = orderExtendMapper.insert(orderVO);
						if (insertOrder > 0) {
							TLog log = new TLog();
							log.setDataId(orderVO.getId());
							log.setTableName(tableNameOrder);
							log.setOperationUser(getCurrentUser().getRealname());
							log.setOperationType(1);
							log.setCreateTime(date);
							log.setUpdateTime(date);
							tLogMapper.insert(log);
						}
					}
					Map<String, Object> importMap = importOrderDetail(date, orderId, orderVO);
					if(MapUtils.getInteger(importMap, "flag") == 1){
						orderMap2.put("describe", MapUtils.getString(importMap, "describe"));
						indexMap.put(index, orderMap2);
					}else{
						orderMap2.put("describe", MapUtils.getString(importMap, "describe"));
						indexMap.put(index, orderMap2);
						continue errorForeach;
					}
				}
			}
			//更新订单板位数
			TOrder order = new TOrder();
			order.setId(orderId);
			order.setTransportUnit(totalTransportBoard);
			tOrderMapper.updateByPrimaryKeySelective(order);
		}
		return indexMap;
	}
	
	/**分类好导入的订单信息后，进行数据处理
	 * @author Fay
	 * @date 2018年5月25日 下午1:17:46
	 * @param sameOrderMap
	 * @return
	 * @throws Exception 
	 */
	public Map<Integer, Map> handleData2(Map<String, Map<Integer, OrderVO>> sameOrderMap){
		Date date = new Date();
//		String nowDate = YYYYMMDD_1.format(date);
		//记录订单的子单号Map
//		Map<String, Integer> order_sys_Map = new HashMap<>();
		
		//记录信息在第几条
		Map<Integer, Map> indexMap = new HashMap<>();
		//记录本次同一个orderId只删除一次
//		Map<Long, Long> deleteOrderIdMap = new HashMap<>();
		if(sameOrderMap == null){
			return indexMap;
		}
		errorForeach: for(String key : sameOrderMap.keySet()){
			Map<Integer, OrderVO> orderList = sameOrderMap.get(key);//通过ic得到每行数据
			
//			BigDecimal totalTransportBoard = new BigDecimal(0);
//			Integer index_ = null;//记录
//			for(Integer index : orderList.keySet()){
//				index_ = index;
//				OrderVO orderVO = orderList.get(index);
//				// 循环时，统计板位数总和，方便等下判断板位数是否符合站点板位数
//				List<OrderDetailVO> orderDetailList = orderVO.getOrderDetailList();
//				// 导入进来的订单详细只有一条
//				OrderDetailVO orderDetailVO = orderDetailList.get(0);
//				BigDecimal transportBoard = orderDetailVO.getTransportBoard();
//				totalTransportBoard = totalTransportBoard.add(transportBoard);
//			}
//			//判断板位数是否与站点的板位数相匹配(大家的key值相同，即装货点、卸货点都相同，因此取一条就可以了)
//			Map<String, Object> judgeTransportUnitFitBranch = this.judgeTransportUnitFitBranch(orderList.get(index_).getStartPlaceId(),
//					orderList.get(index_).getEndPlaceId(), totalTransportBoard);
//			if (!MapUtils.getBoolean(judgeTransportUnitFitBranch, "flag")) {
//				for(Integer index : orderList.keySet()){
//					OrderVO orderVO = orderList.get(index);
//					Map<String, Object> orderMap = getOrderMap(orderVO);
//					orderMap.put("describe", MapUtils.getString(judgeTransportUnitFitBranch, "describe"));
//					indexMap.put(index, orderMap);
//				}
//				continue errorForeach;
//			}
//			//查询订单是否存在该标识
//			TOrderExample example = new TOrderExample();
//			example.createCriteria().andIdentificationNameEqualTo(key);
//			List<TOrder> selectIdenNameList = tOrderMapper.selectByExample(example);
//			
//			Long orderId = null;
//			if(selectIdenNameList != null && selectIdenNameList.size() > 0){
//				orderId = selectIdenNameList.get(0).getId();
//				Byte executeStatus = selectIdenNameList.get(0).getExecuteStatus();
//				Byte generateStatus = selectIdenNameList.get(0).getGenerateStatus();
//				if(executeStatus != 0 || generateStatus != 0){
//					for(Integer index : orderList.keySet()){
//						OrderVO orderVO = orderList.get(index);
//						Map<String, Object> orderMap = getOrderMap(orderVO);
//						orderMap.put("describe", "由于订单已生成或已执行，因此不能再导入数据");
//						indexMap.put(index, orderMap);
//					}
//					continue errorForeach;
//				}
//				if(deleteOrderIdMap.get(orderId) == null){
//					// 证明存在的话，在原本的订单里面先删除原先的物料详细，再新增。只删除一次
//					TOrderDetailExample tOrderDetailExample = new TOrderDetailExample();
//					tOrderDetailExample.createCriteria().andOrderIdEqualTo(orderId);
//					tOrderDetailMapper.deleteByExample(tOrderDetailExample);
//					deleteOrderIdMap.put(orderId, orderId);
//				}
//				for(Integer index : orderList.keySet()){
//					OrderVO orderVO = orderList.get(index);
//					Map<String, Object> orderMap = getOrderMap(orderVO);
//					Map<String, Object> importMap = importOrderDetail(date, orderId, orderVO);
//					if(MapUtils.getInteger(importMap, "flag") == 1){
//						orderMap.put("describe", MapUtils.getString(importMap, "describe"));
//						indexMap.put(index, orderMap);
//					}else{
//						orderMap.put("describe", MapUtils.getString(importMap, "describe"));
//						indexMap.put(index, orderMap);
//						continue errorForeach;
//					}
//				}
//			}else{
//				for(Integer index : orderList.keySet()){
//					OrderVO orderVO = orderList.get(index);
//					Map<String, Object> orderMap2 = getOrderMap(orderVO);
//					//订单重复只需要保存第一个
//					orderVO.setCreateTime(date);
//					orderVO.setUpdateTime(date);
//					orderVO.setTransportUnit(totalTransportBoard);
//					orderVO.setIdentificationName(key);
//					orderVO.setGenerateStatus((byte)0);
//					orderVO.setExecuteStatus((byte)0);
//					orderVO.setEntrySource((byte)0);
//					int insertOrder = orderExtendMapper.insert(orderVO);
//					if (insertOrder > 0) {
//						orderId = orderVO.getId();
//						TLog log = new TLog();
//						log.setDataId(orderId);
//						log.setTableName(tableNameOrder);
//						log.setOperationUser(getCurrentUser().getRealname());
//						log.setOperationType(1);
//						log.setCreateTime(date);
//						log.setUpdateTime(date);
//						tLogMapper.insert(log);
//					}
//					Map<String, Object> importMap = importOrderDetail(date, orderId, orderVO);//保存明细
//					if(MapUtils.getInteger(importMap, "flag") == 1){
//						orderMap2.put("describe", MapUtils.getString(importMap, "describe"));
//						indexMap.put(index, orderMap2);
//					}else{
//						orderMap2.put("describe", MapUtils.getString(importMap, "describe"));
//						indexMap.put(index, orderMap2);
//						continue errorForeach;
//					}
//				}
//			}
			for(Integer index : orderList.keySet()){
				OrderVO orderVO = orderList.get(index);
				Map<String, Object> orderMap2 = getOrderMap(orderVO);
				//订单重复只需要保存第一个
				orderVO.setCreateTime(date);
				orderVO.setUpdateTime(date);
				orderVO.setIdentificationName(key);
				orderVO.setGenerateStatus((byte)0);
				orderVO.setExecuteStatus((byte)0);
				orderVO.setEntrySource((byte)0);
				int insertOrder = orderExtendMapper.insert(orderVO);
				if (insertOrder > 0) {
					TLog log = new TLog();
					log.setDataId(orderVO.getId());
					log.setTableName(tableNameOrder);
					log.setOperationUser(getCurrentUser().getRealname());
					log.setOperationType(1);
					log.setCreateTime(date);
					log.setUpdateTime(date);
					tLogMapper.insert(log);
				}
				Map<String, Object> importMap = importOrderDetail(date, orderVO.getId(), orderVO);//保存明细
				if(MapUtils.getInteger(importMap, "flag") == 1){
					orderMap2.put("describe", MapUtils.getString(importMap, "describe"));
					indexMap.put(index, orderMap2);
				}else{
					orderMap2.put("describe", MapUtils.getString(importMap, "describe"));
					indexMap.put(index, orderMap2);
					continue errorForeach;
				}
			}
			//更新订单板位数
//			TOrder order = new TOrder();
//			order.setId(orderId);
//			order.setTransportUnit(totalTransportBoard);
//			tOrderMapper.updateByPrimaryKeySelective(order);
		}
		return indexMap;
	}
	
	private Map<String, Object> getOrderMap(OrderVO orderVO){
		Map<String, Object> orderMap = new HashMap<>();
		orderMap.put("orderDate", YYYYMMDD.format(orderVO.getOrderDate()));
		orderMap.put("orderNo", orderVO.getOrderNo());
		orderMap.put("startPlaceName", orderVO.getStartPlaceName());
		orderMap.put("endPlaceName", orderVO.getEndPlaceName());
		orderMap.put("earlyDeliveryTime", YYYYMMDDHHMMSS_.format(orderVO.getEarlyDeliveryTime()));
		orderMap.put("lastDeliveryTime", YYYYMMDDHHMMSS_.format(orderVO.getLastDeliveryTime()));
		orderMap.put("applyDepartment", orderVO.getApplyDepartment());
		orderMap.put("materielNo", orderVO.getOrderDetailList().get(0).getMaterielNo());
		orderMap.put("materielName", orderVO.getOrderDetailList().get(0).getMaterielName());
		orderMap.put("transportBoard", orderVO.getOrderDetailList().get(0).getTransportBoard().toString());
		orderMap.put("planNumber", orderVO.getOrderDetailList().get(0).getPlanNumber().toString());
		orderMap.put("unloadingLift", orderVO.getOrderDetailList().get(0).getUnloadingLift());
		return orderMap;
	}

	/**导入功能：订单新增物料
	 * @author Fay
	 * @date 2018年5月25日 下午3:07:19
	 * @param date
	 * @param transUnit
	 * @param orderId
	 * @param orderVO
	 * @return
	 */
	public Map<String, Object> importOrderDetail(Date date, Long orderId, OrderVO orderVO){
		Map<String, Object> resultMap = new HashMap<>();
		
		// 开始储存物料信息
		List<OrderDetailVO> orderDetailList = orderVO.getOrderDetailList();
		OrderDetailVO orderDetailVO = orderDetailList.get(0);
		
		// 查询物料是否存在
		Map<String, Object> materielNoFalg = this.judgeMaterielNoExist(orderDetailVO.getMaterielNo());
		if (MapUtils.getInteger(materielNoFalg, "flag") > 0) {
			orderDetailVO.setMaterielId(MapUtils.getLong(materielNoFalg, "id"));
		}else {//不存在则新增
			TMateriel materiel = new TMateriel();
			materiel.setMaterielName(orderDetailVO.getMaterielName());
			materiel.setMaterielNo(orderDetailVO.getMaterielNo());
			materiel.setCreateTime(date);
			materiel.setUpdateTime(date);
			int id = materielExtendMapper.insert(materiel);
			if (id > 0) {
				TLog log = new TLog();
				log.setDataId(materiel.getId());
				log.setTableName(tableNameMateriel);
				log.setOperationUser(getCurrentUser().getRealname());
				log.setOperationType(1);
				log.setCreateTime(date);
				log.setUpdateTime(date);
				tLogMapper.insert(log);
			}
			orderDetailVO.setMaterielId(materiel.getId());
		}
		//查询订单是否存在该物料详细，存在直接更新，不存在才新增(由于事务的原因查询不了)
		TOrderDetailExample detailExample = new TOrderDetailExample();
		detailExample.createCriteria().andOrderIdEqualTo(orderId).andMaterielIdEqualTo(orderDetailVO.getMaterielId());
		List<TOrderDetail> selectDetailList = tOrderDetailMapper.selectByExample(detailExample);
		if(selectDetailList != null && selectDetailList.size() > 0){
			//存在，则更新即可
			TOrderDetail tOrderDetail = selectDetailList.get(0);
			if(orderDetailVO.getTransportBoard() ==null) orderDetailVO.setTransportBoard(new BigDecimal(0));
			Integer planNum = tOrderDetail.getPlanNumber()+ orderDetailVO.getPlanNumber();
			tOrderDetail.setPlanNumber(planNum);
			tOrderDetail.setTransportBoard(tOrderDetail.getTransportBoard().add(orderDetailVO.getTransportBoard()));
			tOrderDetail.setUpdateTime(date);
			tOrderDetailMapper.updateByPrimaryKeySelective(tOrderDetail);
			resultMap.put("flag", 1);
			resultMap.put("describe", "导入成功");
			return resultMap;
		}else{
			//关联订单与物料的中间表，保存数量、板位等信息
			TOrderDetail tOrderDetail = new TOrderDetail();
			if(orderId == null){
				resultMap.put("describe", "导入异常");
				resultMap.put("flag", 0);
				return resultMap;
			}
			tOrderDetail.setOrderId(orderId);
			tOrderDetail.setMaterielId(orderDetailVO.getMaterielId());
			tOrderDetail.setPlanNumber(orderDetailVO.getPlanNumber());
			
			tOrderDetail.setTransportBoard(orderDetailVO.getTransportBoard());
			tOrderDetail.setUnloadingLift(orderDetailVO.getUnloadingLift());
			tOrderDetail.setCreateTime(date);
			tOrderDetail.setUpdateTime(date);
			int insertSelective = tOrderDetailMapper.insertSelective(tOrderDetail);
			if(insertSelective < 1){
				resultMap.put("describe", "导入异常");
				resultMap.put("flag", 0);
				return resultMap;
			}
			resultMap.put("flag", 1);
			resultMap.put("describe", "导入成功");
		}
		return resultMap;
	}

	@Override
	public List<TOrderDetail> listOrderDetailByMaterielId(Long id) throws Exception {
		if(id == null || id <= 0){
            throw new RuntimeException("id不能为空或者少于等于0！");
        }
		return orderExtendMapper.listOrderDetailByMaterielId(id);
	}

	@Override
	public void updateOrderGenerateStatus(int i, Long taskId, Date date) throws Exception {
		Map<String, Object> map = new HashMap<>();
		map.put("statusNum", i);
		map.put("taskId", taskId);
		map.put("updateTime", date);
		orderExtendMapper.updateOrderGenerateStatus(map);
	}

	@Override
	public List<OrderVO> listOrderByOrderIds(String[] ids) {
		return orderExtendMapper.listOrderByOrderIds(ids);
	}

	@Override
	public List<InterfaceVO> dispatchLoadGirdData(InterfaceGirdQuery queryParam) {
		if(StringUtils.isBlank(queryParam.getSortStr())){
    		queryParam.setSort(0);
    		queryParam.setSortStr("id DESC");
    	}
		List<InterfaceVO> interfaceList = orderExtendMapper.dispatchLoadGirdData(queryParam);
		return interfaceList;
	}
	
}
